import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '@/views/home/home.vue'
import IndexView from '@/views/home/index.vue'
import ClaView from '@/views/home/cla.vue'
import CartView from '@/views/home/cart.vue'
import MyView from '@/views/home/my.vue'
import loginView from '@/views/login/index.vue'
import registerView from '@/views/register/index.vue'
import searchView from '@/views/search/index.vue'
import goodsView from '@/views/goods/index.vue'
import DetailView from '@/views/detail/index.vue'
import orderdetailView from '@/views/order/index.vue'
import myorderView from '@/views/order/myorder.vue'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    // {path: '/',name: 'home',component: HomeView},
    // 重定向
    { path: '/', redirect: '/home/index' },
    {
      path: '/home', name: 'home', component: HomeView, children: [
        { path: 'index', name: 'index', component: IndexView },
        { path: 'cla', name: 'cla', component: ClaView },
        { path: 'cart', name: 'cart', component: CartView },
        { path: 'my', name: 'my', component: MyView },
      ]
    },
    //登录
    { path: '/login', name: 'login', component: loginView },
    //注册
    { path: '/register', name: 'register', component: registerView },
    // 搜索
    { path: '/search', name: 'search', component: searchView },
    //商品列表
    { path: '/goods/:cat_name', name: 'goods', component: goodsView },
    // 商品详情页 -- params 传参
    { path: '/detail/:goods_id', name: 'detail', component: DetailView },
    // 订单详情
    { path: '/orderdetail/:orderId', name: 'orderdetail', component: orderdetailView },
    // 订单列表
     // 搜索
    { path: '/myorder', name: 'myorder', component: myorderView },
  ],
})

// 导航守卫
router.beforeEach((to, from, next) => {
  if (to.fullPath == '/home/cart' || to.fullPath == '/home/my') {
    let token = localStorage.getItem('token');
    if (token) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  }
})
export default router
